package com.cb2.algorithm.leetcode;

import java.util.LinkedList;
import java.util.Queue;

public class Generator {
    public static ListNode create(int... nums) {
        ListNode dummyHead = new ListNode(-1);
        ListNode currNode = dummyHead;
        for (int num : nums) {
            currNode.next = new ListNode(num);
            currNode = currNode.next;
        }
        return dummyHead.next;
    }

    public static TreeNode buildTree(Integer...arr) {
        if (arr == null || arr.length == 0 || arr[0] == null) {
            return null;
        }
        // 创建根节点
        TreeNode root = new TreeNode(arr[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int idx = 1; // 从数组的第二个元素开始处理
        while (!queue.isEmpty() && idx < arr.length) {
            TreeNode current = queue.poll();

            // 处理左子节点
            if (arr[idx] != null) {
                current.left = new TreeNode(arr[idx]);
                queue.offer(current.left);
            }
            idx++;

            // 处理右子节点
            if (idx < arr.length && arr[idx] != null) {
                current.right = new TreeNode(arr[idx]);
                queue.offer(current.right);
            }
            idx++;
        }
        return root;
    }
}
